package com.kdg.quene.arrayblockquene;

import java.util.PriorityQueue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 普通生产者和消费者
 * @author kong
 */
public class GeneralProducerConsumer {
    private int queneSize = 10;
    private PriorityQueue<Integer> quene = new PriorityQueue<>(queneSize);

    public static void main(String[] args) {
        //创建一个公平的阻塞队列
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(100,true);
        try {
            arrayBlockingQueue.put("123");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //普通生产者和消费者测试   --使用的是wait()和notify()线程交互
        GeneralProducerConsumer queneTestOne = new GeneralProducerConsumer();
        Producer producer = queneTestOne.new Producer();
        Consumer consumer = queneTestOne.new Consumer();
        producer.start();
        consumer.start();

    }

    class Consumer extends Thread {
        @Override
        public void run() {
            consume();
        }

        private void consume() {
            while (true) {
                synchronized (quene) {
                    while (quene.size() == 0) {
                        try {
                            System.out.println();
                            quene.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            quene.notify();
                        }
                    }
                    quene.poll(); //每次移走队首元素
                    quene.notify();
                    System.out.println("从队列取走一个元素，队列剩余+" + quene.size() + "各元素");
                }
            }
        }
    }

    class Producer extends Thread {
        @Override
        public void run() {
            produce();
        }

        private void produce() {
            while (true) {
                synchronized (quene) {
                    while (quene.size() == queneSize) {
                        try {
                            System.out.println("队列满，等待有空余空间");
                            quene.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            quene.notify();
                        }
                    }
                    quene.offer(1); //每次插入一个元素
                    quene.notify();
                    System.out.println("向对列插入一个元素，队列剩余空间：" + (queneSize - quene.size()));
                }
            }
        }
    }
}
